package com.example;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle {
    private String beanName;
    private BeanFactory beanFactory;
    private ApplicationContext applicationContext;
    private boolean isRunning;

    // 实现 BeanNameAware 接口的方法
    @Override
    public void setBeanName(String name) {
        System.out.println("BeanNameAware: Bean 的名称被设置为 " + name);
        this.beanName = name;
    }

    // 实现 BeanFactoryAware 接口的方法
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware: BeanFactory 被设置为 " + beanFactory);
        this.beanFactory = beanFactory;
    }

    // 实现 ApplicationContextAware 接口的方法
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware: ApplicationContext 被设置为 " + applicationContext);
        this.applicationContext = applicationContext;
    }

    // 使用 @PostConstruct 注解定义初始化方法
    @PostConstruct
    public void postConstruct() {
        System.out.println("@PostConstruct: Bean 初始化前执行的方法");
    }

    // 实现 InitializingBean 接口的方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean: Bean 属性设置完成后执行的方法");
    }

    // 自定义初始化方法
    public void customInit() {
        System.out.println("自定义初始化方法: 执行自定义的初始化逻辑");
    }

    // 实现 SmartLifecycle 接口的方法
    @Override
    public void start() {
        System.out.println("SmartLifecycle: 启动 Bean");
        isRunning = true;
    }

    @Override
    public void stop() {
        System.out.println("SmartLifecycle: 停止 Bean");
        isRunning = false;
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }

    // 使用 @PreDestroy 注解定义销毁方法
    @PreDestroy
    public void preDestroy() {
        System.out.println("@PreDestroy: Bean 销毁前执行的方法");
    }

    // 实现 DisposableBean 接口的方法
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean: Bean 销毁时执行的方法");
    }

    // 自定义销毁方法
    public void customDestroy() {
        System.out.println("自定义销毁方法: 执行自定义的销毁逻辑");
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable callback) {
        stop();
        callback.run();
    }

    @Override
    public int getPhase() {
        return 0;
    }
}
